package com.teacher.hong.servlet;

import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.utils.ServletUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Enumeration;

@WebServlet("/myHttpGet")
public class MyHttpGetServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("当前Method:" + req.getMethod());
        System.out.println("当前URI:" + req.getRequestURI());
        System.out.println("当前QueryString:" + req.getQueryString());
        System.out.println("ServletPath:" + req.getServletPath());
        System.out.println("RemoteHost:" + req.getRemoteHost());
        System.out.println("RemoteAddr:" + req.getRemoteAddr());

        System.out.println("Header里面的User-Agent:" + req.getHeader("User-Agent"));
        System.out.println("Header里面的Token:" + req.getHeader("Token"));
        Enumeration<String> headerNames = req.getHeaderNames();
        //用一个while循环去循环headerNames里面的值，循环条件是 headerNames还有更多的元素吗？
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println("循环中的headerName：" + headerName+ ",\t值：" + req.getHeader(headerName));
        }
        System.out.println("请求的ContentType:" + req.getContentType());

        System.out.println("参数age:" + req.getParameter("age"));
        System.out.println("参数sex:" + req.getParameter("sex"));

        ServletUtils.recordVisits(getServletContext());

        /**
         * 操作了一堆我们代码
         */
        JSONObject object = new JSONObject(true);
        object.put("state", 200);
        JSONObject value = new JSONObject(true);
        value.put("id", 1001);
        value.put("name", "jack");
        value.put("age", 20);
        value.put("sex", "男");

        object.put("value", value);
        object.put("timestamp", LocalDateTime.now());

        resp.setStatus(402);

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(object.toJSONString());


    }
}
